package com.wangwenjun.concurrency.chapter14.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Package: com.wangwenjun.concurrency.chapter14
 * @ClassName: UseSemaphore
 * @Author: lujieni
 * @Description: 使用Semaphore
 * @Date: 2021-03-09 13:51
 * @Version: 1.0
 *
 * semaphore.acquire() 获得允许,假如已经满了就等待
 * semaphore.release() 释放,会将当前的信号量释放+1,然后唤醒等待的线程
 */
public class UseSemaphore2 {

    public static void main(String[] args)  {

        Semaphore semaphore = new Semaphore(5);

        for (int i = 0; i < 7; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                try{
                    System.out.println(Thread.currentThread().getName()+" 开始干活");
                    Thread.sleep(2_000);
                }catch (Exception e){
                }finally {
                    System.out.println(Thread.currentThread().getName()+" 结束工作");
                    semaphore.release();
                }
            }, "线程:" + i).start();
        }
    }
}